<template>
  <div class="app-container">
    <el-form size="small" :inline="true">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addPolygon()">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" @click="editPolygon()">修改围栏范围</el-button>
        </el-col>
        <el-col :span="1.5" v-if="delectBtnShow">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="delectPolygon()">删除</el-button>
        </el-col>
        <el-col :span="1.5" v-if="saveBtnShow">
          <el-button type="primary" icon="el-icon-check" size="mini" @click="submitData(1)">保存更改</el-button>
        </el-col>
        <el-col :span="1.5" v-if="closeBtnShow">
          <el-button plain icon="el-icon-close" size="mini" @click="submitData(2)">取消更改</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div class="section">
      <ul class="menu" :style="{width:polygonArr.length > 0 ? '160px' : '0px'}">
        <li v-for="(item,index) in polygonArr" :key="
        index" @click="editMap(item,index)" class="menu_item" :class="activeMenu === index ? 'active' : ''">
          <div class="menu_item_all">
            <span class="menu_item_text">{{item._opts.extData.name}}</span>
            <div>
              <el-button plain type="primary" icon="el-icon-edit" size="mini" class="menu_item_btn" @click.prevent="editName(item)"></el-button>
            </div>
          </div>
        </li>
      </ul>
      <div id="container"></div>
    </div>
    <!-- 新增或者修改电子围栏时弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogShow" append-to-body>
      <el-form :model="model" :rules="rule" ref="customform" label-width="150px">
        <el-form-item label="请输入名称：" prop="name">
          <el-input v-model="model.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="请选择围栏颜色：" prop="fillColor">
          <el-color-picker v-model="model.fillColor"></el-color-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="formSubmitHandle()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMapRegion, update } from "@/api/map/mapshow";
// import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "map-view",
  data() {
    return {
      polyEditor: null, //多边形编舞器
      mouseTool: null,
      pathArr: [], //获后台模赵数据
      removePoly: '',
      polygonArr: [], //地图上所有的多边形
      isEdit: false, //是否处于可编状态
      delectArr: {}, ///删除的多边形数据
      activeMenu: '', //被选中的左侧地区菜单
      centerMarker: [119.542197, 39.943673], //初始化地图中心点
      delectBtnShow: false, //删除按钮显示
      saveBtnShow: false, //保存按钮显示
      closeBtnShow: false, //取消按钮显示
      map: null, // 地图组件
      dialogTitle:"", //新增或者修改电子围栏时弹窗的标题
      confirmLoading:false, //新增或者修改电子围栏时弹窗的防抖
      dialogShow:false, //新增或者修改电子围栏时弹窗显示
      model:{ //新增或者修改电子围栏时弹窗的数据
        name:"",
        fillColor:"",
        path:""
      }, 
      rule:{ //新增或者修改电子围栏时弹窗的数据规则
        name:[
        {
          required:true,
          message:"请输入名称",
          trigger:"blur"
        }
        ],
        fillColor:[
        {
          required:true,
          message:"请选择围栏颜色",
          trigger:"change"
        }
        ]
      }, 
    };
  },
  mounted() {
    this.$nextTick(function () {
      this.initAMap();
    });
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    // 初始化地图
    initAMap() {
      this.map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 17, // 初始化地图级别
        center: this.centerMarker, // 初始化地图中心点位置
        // location: [119.542197, 39.943673], //地图中心点
      });
      this.getInitMapData() //绘制已经有的数据
    },
    // 获取地图上多边形数据
    getInitMapData() {
      var dealpolygonArr = []
      this.pathArr = []
      this.polygonArr = []
      var data = {
        name: "map_coordinate",
      }
      getMapRegion(data).then(response => {
        this.pathArr = response.data ? response.data : []
        this.pathArr && this.pathArr.forEach((el) => {
          var polygon = new AMap.Polygon({
            strokeColor:el.fillColor,
            fillColor:el.fillColor,
            path: el.path,
            fillopacity: .3,
            strokeweight: 3,
            strokeOpacity: 1,
            ZIndex: 1,
            extData: {
              name: el.name
            }
          })
          dealpolygonArr.push(polygon)
          this.polygonArr = dealpolygonArr
        })
        this.map.add(this.polygonArr)
        this.map.setFitView(this.polygonArr)
        this.polyEditor = new AMap.PolygonEditor(this.map); //编辑多边形事件
        this.polyEditor._opt.createOptions = {// 创建区城的样式
          fillopacity: .3,
          strokeweight: 3,
          strokeOpacity: 1,
        }
        this.polyEditor._opt.editOptions = {// 编区城的样式
          fillopacity: .3,
          strokeweight: 3,
          strokeOpacity: 1,
        }
      });
    },
    // 根据多边形最长距离设置zoom
    getPolygonZoom(PolygonArr) {
      let maxL = Math.max(...PolygonArr.map(item => item[0]))
      let minL = Math.min(...PolygonArr.map(item => item[0]))
      let maxK = Math.max(...PolygonArr.map(item => item[1]))
      let minK = Math.min(...PolygonArr.map(item => item[1]))
      let p1 = [maxL, maxK]
      let p2 = [minL, minK]
      let dis = AMap.GeometryUtil.distance(p1, p2);
      let zoom = 12
      let zooms = [[10000, 11], [5000, 12], [2000, 15], [1000, 16], [600, 16.5], [500, 17], [200, 18], [100, 19], [50, 20], [15, 21][10, 22]]
      for (let i = 0; i < zooms.length; i++) {
        let item = zooms[i]
        if (dis > item[0]) {
          zoom = item[1]
          return zoom
        }
      }
    },
    // 获取多边形中心点
    getPolygonCenter(PolygonArr) {
      let total = PolygonArr.length;
      let X = 0;
      let Y = 0;
      let Z = 0;
      PolygonArr.forEach((lnglat) => {
        let lng = lnglat[0] * Math.PI / 180;
        let lat = lnglat[1] * Math.PI / 180;
        let x, y, z;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      });
      X = X / total;
      Y = Y / total;
      Z = Z / total;
      let Lng = Math.atan2(Y, X);
      let Hyp = Math.sqrt(X * X + Y * Y);
      let Lat = Math.atan2(Z, Hyp);
      return [Lng * 180 / Math.PI, Lat * 180 / Math.PI]
    },
    // 循环多边形处理
    forPolyEditor() {
      var self = this;
      self.polygonArr && self.polygonArr.forEach((polygon, index) => {
        //多边形添加双击事件
        polygon.on('click', () => {
          let center = this.getPolygonCenter(polygon._opts.path)
          let zoom = this.getPolygonZoom(polygon._opts.path)
          self.map.setZoomAndCenter(zoom, center, true);
          self.delectArr = polygon
          self.activeMenu = index
          if (self.polyEditor) {
            self.polyEditor.setTarget(polygon);
            self.polyEditor.open();
            self.isEdit = true;
          }
        })
      })
    },
    // 添加多边形
    addPolygon() {
      this.delectArr = {}
      this.polyEditor.close();
      this.closeDialog()
      this.dialogShow =true;
      this.dialogTitle = "新增电子围栏"
      // this.$prompt('请输入名称', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      // }).then(({ value }) => {
      //   self.polyEditor.setTarget();
      //   self.polyEditor.open();
      //   self.isEdit = true
      //   // 多边形添加
      //   let names = []
      //   self.polyEditor.on('add', function (data) {
      //     if (names.includes(value))
      //       return
      //     data.target._opts.extData.name = value
      //     var polygon = data.target;
      //     self.polygonArr.push(polygon);
      //     self.polyEditor.addAdsorbPolygons(self.polygonArr);
      //     self.delectArr = polygon
      //     names.push(value)
      //     self.delectBtnShow = true//删除按钮显示
      //     self.saveBtnShow = true //保存按钮显示
      //     self.closeBtnShow = true //取消按钮显示
      //   })
      // }).catch(() => { });

    },
    // 编辑
    editPolygon() {
      this.polyEditor.addAdsorbPolygons(this.polygonArr);
      this.forPolyEditor()
      this.isEdit = true
      this.delectBtnShow = true//删除按钮显示
      this.saveBtnShow = true //保存按钮显示
      this.closeBtnShow = true //取消按钮显示
    },
    // 修改菜单定位名称
    editName(item) {
      this.dialogShow =true;
      this.isEdit = true
      this.dialogTitle = "修改电子围栏"
      this.model.name = item._opts.extData.name
      this.model.fillColor = item._opts.fillColor
      this.model.path = item._opts.path.toString()
      // var self = this;
      // this.$prompt('请输入名称', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   inputValue: item._opts.extData.name
      // }).then(({ value }) => {
      //   self.isEdit = true
      //   item._opts.extData.name = value
      //   self.polygonArr.map((itemin, index) => {
      //     if (itemin._opts.path.toString() == item._opts.path.toString()) {
      //       itemin._opts.name = value
      //       this.$set(self.polygonArr, index, itemin)
      //     }
      //   });
      // }).catch(() => { });
    },
    // 点击菜单栏对多边形进行选择编辑
    editMap(item, index) {
      this.activeMenu = index
      this.polyEditor.setTarget(item);
      this.polyEditor.open();
      this.delectArr = item
      let center = this.getPolygonCenter(item._opts.path)
      let zoom = this.getPolygonZoom(item._opts.path)
      this.map.setZoomAndCenter(zoom, center, true);
      this.delectBtnShow = true//删除按钮显示
      this.saveBtnShow = true //保存按钮显示
      this.closeBtnShow = true //取消按钮显示
    },
    // 删除多边形操作
    delectPolygon() {
      if (this.delectArr !== {}) {
        this.removePolygon(this.delectArr)
      } else {
        this.$message({
          message: '请先选择地区',
          type: 'warning'
        });
      }
    },
    // 删除某个多边形
    removePolygon(onePolygon) {
      this.polyEditor.close(); //关闭编舞器
      this.map.remove(onePolygon);
      // 获覆盖物
      var overlays = this.map.getAllOverlays('polygon');
      this.polygonArr = overlays
      // this.polygonArr.remove(onePolygon)
      this.delectArr = {}
    },
    // 关闭电子围栏弹窗
    closeDialog(){
      this.dialogShow =false;
      this.dialogTitle = "";
      this.$refs.customform.resetFields()
      this.model={
        name:"",
        fillColor:"",
        path:""
      }
    },
    // 新增或者修改电子围栏时弹窗提交
    formSubmitHandle(){
      var self=this;
      this.$refs.customform.validate(valid => {
        if (valid) {
          let value =self.model.name
          let fillColor =self.model.fillColor
          if(self.dialogTitle == '新增电子围栏'){
            // 判断名称是否与现有重复
            let names =[]
            self.polygonArr.map((item)=>{
              names.push(item._opts.extData.name)
            })
            if(names.includes(self.model.name)){
              self.$message({
                message: '名称重复',
                type: 'warning'
              });
              return
            }
            self.polyEditor.setTarget();
            self.polyEditor.open();
            self.isEdit = true
            // 多边形添加
            let nameArr = []
            self.polyEditor.on('add', function (data) {
              if (nameArr.includes(value))
              return
              data.target._opts.extData.name = value
              data.target._opts.fillColor = fillColor
              data.target._opts.strokeColor = fillColor
              var polygon = data.target;
              self.polygonArr.push(polygon);
              self.polyEditor.addAdsorbPolygons(self.polygonArr);
              self.delectArr = polygon
              nameArr.push(value)
              self.delectBtnShow = true//删除按钮显示
              self.saveBtnShow = true //保存按钮显示
              self.closeBtnShow = true //取消按钮显示
            })
            // 清空数据和校验
             self.closeDialog()
          }
          else{
            self.polygonArr.map((itemin, index) => {
              if (itemin._opts.path.toString() == self.model.path) {
                itemin._opts.extData.name = value
                itemin._opts.fillColor = fillColor
                self.$set(self.polygonArr, index, itemin)
                itemin.setOptions({
                  fillColor:fillColor,
                  strokeColor:fillColor,
                  fillopacity: .3,
                  strokeweight: 3,
                  strokeOpacity: 1,
                  extData: {
                    name: value
                  }
                })
              }
            });
            // 清空数据和校验
             self.closeDialog()
          }
        }
      });
    },
    // 保存绘制数据
    submitData(flag) {
      this.isEdit = false;
      this.delectBtnShow = false //删除按钮显示
      this.saveBtnShow = false //保存按钮显示
      this.closeBtnShow = false //取消按钮显示
      this.activeMenu = ''
      // // flag == 2 取消按钮 flag==1 是保存按钮
      if (flag == 2) {
        this.polyEditor = null;
        this.polyEditor.close();
        this.map.clearMap();
        this.getInitMapData()
      }
      else {
        let arr = []
        this.polygonArr.map(item => {
          arr.push({ path: item._opts.path, name: item._opts.extData.name, fillColor: item._opts.fillColor})
        });
        // _opts.path 是定位坐标
        var data = {
          name: 'map_coordinate',
          value: JSON.stringify(arr)
        }
        update(data).then(response => {
          this.$modal.msgSuccess("保存成功");
          this.polyEditor.close();
          this.map.clearMap();
          this.getInitMapData()
        });
      }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.section {
  display: flex;
  .menu {
    // max-width: 200px;
    height: 600px;
    overflow-y: scroll;
    font-size: 14px;
    list-style: none;
    padding: 0;
    margin: 0;
    .menu_item {
      cursor: pointer;
      line-height: 30px;
      &.active {
        color: #409eff;
      }
      .menu_item_all {
        &:hover {
          .menu_item_btn {
            display: inline-block;
          }
        }
        display: flex;
        .menu_item_text {
          display: inline-block;
          width: 100px;
          overflow: hidden; /* 隐藏超出部分的内容 */
          white-space: nowrap; /* 禁止文本换行 */
          text-overflow: ellipsis; /* 在文本末尾添加省略号 */
        }
        .menu_item_btn {
          padding: 0;
          margin: 0 6px;
          display: none;
          // &:hover{
          //   display: inline-block;
          // }
          .el-icon-edit {
            // color: #FFF !important;
            font-size: 10px;
            margin: 0;
          }
        }
      }
    }
  }
}
#container {
  width: 100%;
  height: 600px;
}
</style>
